"""搜索记录业务逻辑"""

from typing import Dict

from sqlalchemy.ext.asyncio import AsyncSession

from module_admin.dao.search_record_dao import SearchRecordDao
from module_admin.entity.vo.search_record_vo import (
    SearchRecordModel,
    SearchRecordQueryModel,
)


class SearchRecordService:
    """搜索记录 Service"""

    @classmethod
    async def get_record_list(
        cls,
        db: AsyncSession,
        query_params: SearchRecordQueryModel,
        page_num: int = 1,
        page_size: int = 10
    ) -> Dict:
        records, total = await SearchRecordDao.get_record_list(
            db=db,
            query_params=query_params,
            page_num=page_num,
            page_size=page_size
        )

        record_models = []
        for record in records:
            model = SearchRecordModel.model_validate(record)
            # 统一 item_price 为字符串，便于前端展示
            if model.item_price is not None:
                model.item_price = cls._format_price(model.item_price)
            record_models.append(model)

        return {
            "rows": record_models,
            "total": total
        }

    @staticmethod
    def _format_price(value):
        try:
            return f"{float(value):.2f}"
        except (TypeError, ValueError):
            return str(value) if value is not None else None
